package controller;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.enums.SecuritySchemeType;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.security.SecurityScheme;
import io.swagger.v3.oas.annotations.tags.Tag;
import dto.BidRequest;
import dto.BidResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import service.BiddingService;
import jakarta.validation.Valid;

@RestController
@RequestMapping("/api/bids")
@Tag(name = "投标管理", description = "债券投标操作相关接口")
@SecurityScheme(
        name = "BearerAuth",
        type = SecuritySchemeType.HTTP,
        scheme = "bearer",
        bearerFormat = "JWT"
)
@SecurityRequirement(name = "BearerAuth")
public class BiddingController {
    @Autowired
    private BiddingService biddingService;

    @Operation(
            summary = "提交投标",
            description = "用于客户端提交新的债券投标请求",
            responses = {
                    @io.swagger.v3.oas.annotations.responses.ApiResponse(
                            responseCode = "200",
                            description = "投标成功",
                            useReturnTypeSchema = true
                    ),
                    @io.swagger.v3.oas.annotations.responses.ApiResponse(
                            responseCode = "400",
                            description = "投标失败（金额不足或参数错误）"
                    ),
                    @io.swagger.v3.oas.annotations.responses.ApiResponse(
                            responseCode = "401",
                            description = "未授权访问"
                    )
            }
    )
    @PostMapping("/place")
    public ResponseEntity<BidResult> placeBid(
            @Parameter(description = "投标请求参数", required = true)
            @Valid @RequestBody BidRequest bidRequest,

            @Parameter(
                    description = "JWT认证令牌",
                    required = true,
                    hidden = true // 在文档中隐藏实际参数
            )
            @RequestHeader("Authorization") String token
    ) {
        try {
            boolean isPlaced = biddingService.placeBid(bidRequest);
            return isPlaced ?
                    ResponseEntity.ok(BidResult.success()) :
                    ResponseEntity.status(HttpStatus.BAD_REQUEST)
                            .body(BidResult.fail("出价失败，金额不足"));
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(BidResult.fail("出价过程中出现错误：" + e.getMessage()));
        }
    }
}
